package com.lucy.disk.validator;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.lang.Validator;
import com.lucy.common.constant.HttpStatus;
import com.lucy.common.domain.ResponseDTO;
import com.lucy.common.exception.BusinessException;
import com.lucy.common.validator.IsSex;
import com.lucy.disk.domain.entity.FileEntity;
import com.lucy.disk.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Optional;

public class DirCheckValidator implements ConstraintValidator<DirCheck, Object> {
    @Autowired
    FileService fileService;

    @Override
    public void initialize(DirCheck constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
    }

    @Override
    public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
        String dirId = "";
        if (Validator.isNotEmpty(o)){
            dirId = o.toString();
        }
        Object loginId = StpUtil.getLoginIdDefaultNull();
        Optional<FileEntity> parentOp = fileService.getOne(dirId);
        if (Validator.isNotEmpty(dirId) && !parentOp.isPresent()){
            // 检查目录是否存在 或者为空
            return false;
        }else if (Validator.isNotEmpty(dirId) && parentOp.isPresent()){
            // 检查是否拥有权限
            FileEntity parentDir = parentOp.get();
            if (Validator.isEmpty(loginId)){
                return false;
            }else {
                return parentDir.getUserId().equals(loginId.toString());
            }

        }
        return true;
    }
}
